package com.ktwlsoft.archivemanage.service.security;

import com.ktwlsoft.archivemanage.domain.dao.entity.Account;
import com.ktwlsoft.archivemanage.domain.dao.repository.IAccountMapper;
import com.ktwlsoft.archivemanage.domain.dao.repository.IUserRolesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private IAccountMapper accountMapper;

    @Autowired
    private IUserRolesMapper userRolesMapper;

    @Override
    public UserDetails loadUserByUsername(String usernameOrEmail)
            throws UsernameNotFoundException {
        // Let people login with either username or email
        Account user = accountMapper.findByUserNameOrPhone(usernameOrEmail);
        if (user == null) {
          //  throw new UsernameNotFoundException("没有找到对应账号名或者手机号: " + usernameOrEmail);
            throw new RuntimeException("无此用户");

        }
        List<GrantedAuthority> authorities = userRolesMapper.findRolesByAccountId(user.getId()).stream().map(role ->
                new SimpleGrantedAuthority(role.getRoleName())
        ).collect(Collectors.toList());
        return UserPrincipal.create(user, authorities);
    }

    // This method is used by JWTAuthenticationFilter
    UserDetails loadUserById(Long id) {
        Account user = accountMapper.getById(id);
        if (user == null) {
            throw new UsernameNotFoundException("没有找到对应id的账号 : " + id);
        }
        List<GrantedAuthority> authorities = userRolesMapper.findRolesByAccountId(user.getId()).stream().map(role ->
                new SimpleGrantedAuthority(role.getRoleName())
        ).collect(Collectors.toList());
        return UserPrincipal.create(user, authorities);
    }
}
